import { defineStore } from 'pinia';
import { useTagStore } from './tagStore'; // Import tagStore

export const useChatStore = defineStore('chat', {
  state: () => ({
    messages: [], // ChatMessageModel[]
    currentUserId: null, // string | null
  }),
  getters: {
    sortedMessages: (state) => {
      // Sorts messages by timestamp, assuming timestamp is a sortable string (ISO) or number
      return [...state.messages].sort((a, b) => {
        if (a.timestamp < b.timestamp) return -1;
        if (a.timestamp > b.timestamp) return 1;
        return 0;
      });
    },
    getMessageById: (state) => {
      return (messageId) => state.messages.find(msg => msg.message_id === messageId);
    },
    // New getter starts here
    filteredMessages: (state) => {
      const tagStore = useTagStore();
      const selectedFilterTags = new Set(tagStore.selectedFilterTags); // Use Set for efficient lookup

      // If no tags are selected in the filter, and the intention is to show messages
      // that would match ANY of the active tags (which are all by default),
      // this logic needs to be robust.
      // The current spec implies: if selectedFilterTags is empty, only untagged messages show.
      // If selectedFilterTags has items, messages must match one of them OR be untagged.

      return state.messages.filter(message => {
        // Ensure message.tags is an array, even if null or undefined from source
        const messageTags = Array.isArray(message.tags) ? message.tags : [];

        if (messageTags.length === 0) {
          return true; // Always show messages with no tags
        }
        // Show message if at least one of its tags is in the selectedFilterTags
        return messageTags.some(tag => selectedFilterTags.has(tag));
      });
    }
    // New getter ends here
  },
  actions: {
    setInitialMessages(messages) {
      this.messages = messages || [];
    },
    addMessage(message) {
      // Ensure message is not already in the list to prevent duplicates if backend sends multiple times
      if (message && !this.messages.find(m => m.message_id === message.message_id)) {
        this.messages.push(message);
      }
    },
    setCurrentUserId(userId) {
      this.currentUserId = userId;
    },
    // As per the spec, initial data fetching (including chat) is handled in App.vue
    // and then dispatched to individual stores.
    // So, fetchAndSetInitialChatData() might not be directly needed here if App.vue calls setCurrentUserId and setInitialMessages.

    async requestCopyMessageText(messageId) {
      if (!messageId) {
        console.error('Message ID is required to copy text.');
        // Optionally, use uiStore to set an error
        // const uiStore = useUiStore(); // Pinia stores can be used inside other stores
        // uiStore.setAppError('Message ID is required.');
        return null;
      }
      try {
        const response = await window.pywebview.api.request_copy_original_message_text(messageId);
        if (response.success && response.data) {
          return response.data.original_text;
        } else {
          console.error('Failed to copy message text:', response.error_message);
          // const uiStore = useUiStore();
          // uiStore.setAppError(response.error_message || 'Failed to copy message text.');
          return null;
        }
      } catch (error) {
        console.error('Error copying message text:', error);
        // const uiStore = useUiStore();
        // uiStore.setAppError(`Error copying message text: ${error.message || 'Unknown error'}`);
        return null;
      }
    },
  },
});